package com.nlp.visualization.utils;

import com.nlp.visualization.common.CONSTANTS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;

import java.awt.image.BufferedImage;
import java.io.*;

public class ImageUtils {


    static Logger logger = LoggerFactory.getLogger(ImageUtils.class);

    /**
     * 获取图片宽度
     *
     * @param file 图片文件
     * @return 宽度
     */
    public static int getImgWidth(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int ret = -1;
        try {

            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            ret = src.getWidth(null); // 得到源图宽
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 获取图片高度
     *
     * @param file 图片文件
     * @return 高度
     */
    public static int getImgHeight(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int ret = -1;
        try {

            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            ret = src.getHeight(null); // 得到源图高
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }


    public static File base64ToFile(String base64Code) {
        try {

            String fileName =CONSTANTS.BACKGROUND_IMAGE_PATH +  MD5Util.MD5(System.currentTimeMillis() + "")+ "." + base64Code.split(",")[0].split("image/")[1].split(";")[0];
            base64Code=base64Code.split(",")[1];
            BASE64Decoder decoder = new BASE64Decoder();

                // Base64解码
                byte[] bytes = decoder.decodeBuffer(base64Code);
                for (int i = 0; i < bytes.length; ++i) {
                    if (bytes[i] < 0) {// 调整异常数据
                        bytes[i] += 256;
                    }
                }
                // 生成图片
                OutputStream out = new FileOutputStream(fileName);
                out.write(bytes);
                out.flush();
                out.close();
                return new File(fileName);
        } catch (IOException e) {
            logger.error("base64 转文件失败");
            e.printStackTrace();
            return null;
        }
    }
}
